package com.fuqi.android.zhongcai.business.shuig.view.activity;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.fuqi.android.zhongcai.R;
import com.fuqi.android.zhongcai.base.view.activity.BaseActivity;
import com.fuqi.android.zhongcai.base.view.adapter.BaseRecyclerViewAdapter;
import com.fuqi.android.zhongcai.base.view.adapter.OrderCustomerAdapter;
import com.fuqi.android.zhongcai.base.view.widget.CustomProgress;
import com.fuqi.android.zhongcai.business.shuig.request.api.QueryOrderListByConditionApi;
import com.fuqi.android.zhongcai.business.shuig.request.result.OrderListResult;
import com.fuqi.android.zhongcai.utils.ActivityUtils;
import com.fuqi.android.zhongcai.utils.LogUtils;
import com.fuqi.android.zhongcai.utils.RegexUtil;
import com.fuqi.framework.gson.GsonHelper;
import com.fuqi.framework.network.code.HandleCode;
import com.fuqi.framework.network.http.RequestManager;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

public class OrderSearchListActivity extends BaseActivity {
    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.iv_search_clear)
    ImageView ivSearchClear;
    @Bind(R.id.iv_search)
    ImageView ivSearch;
    @Bind(R.id.recyclerview)
    XRecyclerView mRecyclerView;
    private OrderCustomerAdapter orderCustomerAdapter;
    private List<OrderListResult> orderList;
    String sCondition;
    @Override
    public void initView() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(OrderSearchListActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        orderList = new ArrayList<>();
        orderCustomerAdapter = new OrderCustomerAdapter(this,orderList);
        mRecyclerView.setAdapter(orderCustomerAdapter);

    }

    @Override
    public void initListener() {
        ivSearchClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
                ivSearchClear.setVisibility(View.GONE);
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    ivSearchClear.setVisibility(View.GONE);
                } else {
                    ivSearchClear.setVisibility(View.VISIBLE);
                }
            }
        });
        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (prepare()) {
                    sCondition = etSearch.getText().toString();
                    currentPage = 1;
                    CustomProgress.show(OrderSearchListActivity.this, "正在处理...", true, null);
                    RequestManager.getInstance().call(new QueryOrderListByConditionApi(new QueryOrderListByConditionApi.QueryOrderListByConditionParams(
                            String.valueOf(showCount), String.valueOf(currentPage), sCondition), respOrderListener, errorListener));
                }
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (prepare()) {
                        sCondition = etSearch.getText().toString();
                        currentPage = 1;
                        CustomProgress.show(OrderSearchListActivity.this, "正在处理...", true, null);
                        RequestManager.getInstance().call(new QueryOrderListByConditionApi(new QueryOrderListByConditionApi.QueryOrderListByConditionParams(
                                String.valueOf(showCount), String.valueOf(currentPage), sCondition), respOrderListener, errorListener));
                    }
                }

                return false;
            }
        });
        orderCustomerAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener<OrderListResult>() {
            @Override
            public void onItemClick(View view, int position, OrderListResult data) {

                Bundle bundle = new Bundle();
                bundle.putString("order_id",data.getOrderId());
                bundle.putString("order_type", data.getOrderType());
                ActivityUtils.startActivity(OrderSearchListActivity.this,ShuiGActivity.class,bundle);
//                ActivityUtils.startActivity(MonthPerOrderListActivity.this,OrderDetailActivity.class);
            }
        });
        mRecyclerView.setLoadingMoreEnabled(true);
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                CustomProgress.show(OrderSearchListActivity.this, "正在处理...", true, null);
                RequestManager.getInstance().call(new QueryOrderListByConditionApi(new QueryOrderListByConditionApi.QueryOrderListByConditionParams(
                        String.valueOf(showCount), String.valueOf(currentPage), sCondition), respOrderListener, errorListener));
            }

            @Override
            public void onLoadMore() {
                currentPage ++;
                CustomProgress.show(OrderSearchListActivity.this, "正在处理...", true, null);
                RequestManager.getInstance().call(new QueryOrderListByConditionApi(new QueryOrderListByConditionApi.QueryOrderListByConditionParams(
                        String.valueOf(showCount), String.valueOf(currentPage), sCondition), respOrderListener, errorListener));
            }
        });

    }

    @Override
    public void initData() {

        titleBar.setTitle("订单查询");
    }

    Response.Listener<OrderListResult[]> respOrderListener = new Response.Listener<OrderListResult[]>() {

        @Override
        public void onResponse(OrderListResult[] response) {

            CustomProgress.close();
            if (HandleCode.requestSuccess()) {
                if(response.length == 0)
                    mRecyclerView.noMoreLoading();
                if(currentPage == 1 && orderList != null) {
                    mRecyclerView.setIsnomore(false);
                    orderList.clear();
                }
                for(int i = 0; i < response.length ;i++) {
                    orderList.add(response[i]);
                }

                orderCustomerAdapter.notifyDataSetChanged();
                LogUtils.i( "response OrderListResult: " + GsonHelper.writeValue(response));

            } else {

            }
            mRecyclerView.refreshComplete();
            mRecyclerView.loadMoreComplete();
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            CustomProgress.close();
            mRecyclerView.refreshComplete();
            mRecyclerView.loadMoreComplete();
            Log.i("juner", "juner  error.getMessage(): " + error.getMessage());

        }
    };

    private boolean prepare() {
        if (!RegexUtil.checkNotNull(etSearch.getText())) {
            ActivityUtils.toast("请输入查询条件");
            return false;

        }
        return true;
    }

    @Override
    public boolean hasTitleBar() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_order_search;
    }
}
